﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightPlayground.Net;
using System.Windows.Media.Imaging;
using System.Diagnostics;

namespace SilverlightPlayground.RFB.Readers
{
    public class RRERectReader : RfbClient.RfbRectReader
    {
        public const string ReceivingRREHeader = "ReceivingRREHeader";
        public const string ReceivingRRERect = "ReceivingRRERect";

        /// <summary>
        /// Initializes a new instance of the <see cref="RawRectReader"/> class.
        /// </summary>
        /// <param name="rfb">The RFB.</param>
        public RRERectReader(RfbClient rfb)
            : base(rfb)
        {
#if TRACE
            Debug.WriteLine("RRERectReader.ctor(rfb={0})", rfb.ServerName);
#endif
        }

        /// <summary>
        /// Gets or sets the current rect.
        /// </summary>
        /// <value>The current rect.</value>
        public Rect CurrentRect { get; set; }
        /// <summary>
        /// Gets or sets the frame.
        /// </summary>
        /// <value>The frame.</value>
        private byte[] Frame { get; set; }
        /// <summary>
        /// Gets or sets the bytes per pixel.
        /// </summary>
        /// <value>The bytes per pixel.</value>
        public int BytesPerPixel { get; set; }

        /// <summary>
        /// Reads the specified rect.
        /// </summary>
        /// <param name="rect">The rect.</param>
        public override void Read(Rect rect)
        {
            this.CurrentRect = rect;
            this.Frame = new byte[(int)rect.Width * (int)rect.Height * 4];
            Array.Clear(this.Frame, 0, this.Frame.Length);
            this.BytesPerPixel = this.RFB.BitPerPixel / 8;
            this.Receive(this.BytesPerPixel + 4, RRERectReader.ReceivingRREHeader);
        }

        /// <summary>
        /// Called when [receive].
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="action"></param>
        /// <param name="state"></param>
        public override void OnReceive(byte[] data, string action, object state)
        {
#if TRACE
            Debug.WriteLine("ReceivingRREHeader.OnReceive(data.Length={0})", data.Length);
#endif
            switch (action)
            {
                case RRERectReader.ReceivingRREHeader:
                    this.EndReceiveRREHeader(data);
                    break;
                case RRERectReader.ReceivingRRERect:
                    this.EndReceiveRRERect(data, (int)state);
                    break;
                default:
                    throw new Exception("Unknown status");
            }
        }

        /// <summary>
        /// Ends the receive RRE header.
        /// </summary>
        /// <param name="data">The data.</param>
        private void EndReceiveRREHeader(byte[] data)
        {
#if TRACE
            Debug.WriteLine("ReceivingRREHeader.EndReceiveRREHeader(data.Length={0})", data.Length);
#endif
            int subRectCount = (int)SocketUtilities.ToU32(data, 0);

            if (subRectCount > 0)
            {
                byte [] pixelValue = this.GetColor(data, 4);
                this.FillRect(0, 0, (int)this.CurrentRect.Width, (int)this.CurrentRect.Height, pixelValue);
                this.Receive(this.BytesPerPixel + 8, RRERectReader.ReceivingRRERect, subRectCount);
            }
            else
                this.OnCompleted();
        }

        /// <summary>
        /// Ends the receive RRE rect.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="subRectCount">The sub rect count.</param>
        private void EndReceiveRRERect(byte[] data, int subRectCount)
        {
            byte[] pixelValue = this.GetColor(data, 0);

            this.FillRect(
                SocketUtilities.ToU16(data, this.BytesPerPixel + 0),
                SocketUtilities.ToU16(data, this.BytesPerPixel + 2),
                SocketUtilities.ToU16(data, this.BytesPerPixel + 4),
                SocketUtilities.ToU16(data, this.BytesPerPixel + 6),
                pixelValue);

            if (--subRectCount > 0)
                this.Receive(this.BytesPerPixel + 8, RRERectReader.ReceivingRRERect, subRectCount);
            else
            {
                this.OnRawUpdate(this.CurrentRect, this.Frame);
                this.OnCompleted();
            }
        }

        /// <summary>
        /// Fills the rect.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="pixelValue">The pixel value.</param>
        private void FillRect(int x, int y, int width, int height, byte[] pixelValue)
        {
            //TODO: continuare qui

            //for (int yy = y; yy < y + height; yy++)
            //{
            //    for (int xx = x * 4; xx < (x + width) * 4; xx++)
            //    {
            //        Buffer.BlockCopy(pixelValue, 0, this.Frame, yy * width + xx, 4);
            //    }
            //}
        }

        /// <summary>
        /// Gets the color.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="offset">The offset.</param>
        /// <returns></returns>
        private byte[] GetColor(byte[] data, int offset)
        {
            UInt32 pixel = RfbProtoUtil.GetPixelFromData(data, offset, this.RFB.BytesPerPlane);

            return new byte[] 
            { 
                (byte)(((pixel >> this.RFB.BlueShift) & this.RFB.BlueMax) * 255 / this.RFB.BlueMax), 
                (byte)(((pixel >> this.RFB.GreenShift) & this.RFB.GreenMax) * 255 / this.RFB.GreenMax), 
                (byte)(((pixel >> this.RFB.RedShift) & this.RFB.RedMax) * 255 / this.RFB.RedMax), 
                0xFF 
            };
        }
    }
}
